﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Husb.Util;
using Husb.Util.Enum;
using CentralOffice.Task.Data;
using CentralOffice.Task.BusinessActions;

using ApplicationTable = CentralOffice.Task.Data.ApplicationDataSet.ApplicationsDataTable;
using ApplicationRow = CentralOffice.Task.Data.ApplicationDataSet.ApplicationsRow;

using ApprovalTable = CentralOffice.Task.Data.ApprovalDataSet.ApprovalsDataTable;
using ApprovalRow = CentralOffice.Task.Data.ApprovalDataSet.ApprovalsRow;

using CentralOffice.MyTable.Data;
using CentralOffice.MyTable.BusinessActions;
using Husb.Security;
using CentralOffice.Admin.BusinessActions;

using SmsTable = CentralOffice.MyTable.Data.SmsDataSet.smsDataTable;
using SmsRow = CentralOffice.MyTable.Data.SmsDataSet.smsRow;
using SmsBodyTable = CentralOffice.MyTable.Data.SmsDataSet.sms_bodyDataTable;
using SmsBodyRow = CentralOffice.MyTable.Data.SmsDataSet.sms_bodyRow;

using PaymentTable = CentralOffice.Task.Data.PaymentItemDataSet.PaymentDataTable;
using PaymentRow = CentralOffice.Task.Data.PaymentItemDataSet.PaymentRow;
using System.Web.UI.HtmlControls;
using System.Data;


// http://localhost:1318/tasks/ApplicationPaymentPlanAdd.aspx
// http://localhost:1318/tasks/ApplicationApprove.aspx

namespace CentralOffice.WebClient.Tasks
{
    public partial class Approval : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                string approvalId = HttpContext.Current.Request.QueryString["id"];
                ApprovalRow approval = CentralOffice.Task.BusinessActions.Approvals.GetById(new Guid(approvalId));

                chkIsFinal.Checked = approval.IsFinal;

                //string[] roles = System.Web.Security.Roles.GetRolesForUser();
                //if (roles.Contains("总经理"))
                //{
                //    chkIsFinal.Checked = true;
                //}

                if (approval != null)
                {
                    if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["op"]) && !approval.IsResultApprovedNull())
                    {
                        btnSave.Visible = false;
                        Button1.Visible = false;
                        lblJavaScript.Text = "<script type=\"text/javascript\">alert('本步已审批！');</script>";
                    }

                    if (!String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["op"]))
                    {
                        ApprovalRow approvalNext = CentralOffice.Task.BusinessActions.Approvals.GetByPreviousStepId(approval.Id);
                        if (approvalNext != null && !approvalNext.IsResultApprovedNull())
                        {
                            lblJavaScript.Text = "<script type=\"text/javascript\">alert('下一步已经审批！您不能再修改这一步的审批结果了。');history.back();</script>";
                            return;
                        }
                    }

                    lblName.Text = approval.Name;
                    lblApplicant.Text = approval.Applicant;
                    lblDateOfApplication.Text = approval.DateOfApplication.ToString("yyyy-MM-dd HH:mm:ss");

                    if (!approval.IsAttachmentsNull() && approval.Attachments.Length > 0)
                    {
                        lblAttachments.Visible = true;
                        SiteUtil.GenernateDownloadHyperLink(lblAttachments, approval.Attachments);
                    }

                    lblApprovalContent.Text = approval.IsContentTextNull() ? "" : approval.ContentText.Replace("\n", "<br />");
                    lblDateApproved.Text = approval.IsDateApprovedNull() ? "" : approval.DateApproved.ToString();
                    lblResultApproved.Text = approval.IsResultApprovedNull() ? "" : String.Format("<span class=\"warning\">{0}</span>", approval.ResultApproved ? "已批准" : "未批准");

                    //lblApprovalContent.Text = approval[(approval.Table as ApprovalTable).ApprovalContentColumn.ColumnName] != DBNull.Value ? approval.ApprovalContent : "";
                    lblPreviousContentText.Text = approval[(approval.Table as ApprovalTable).PreviousContentTextColumn.ColumnName] != DBNull.Value ? approval.PreviousContentText.Replace("\n", "<br />") : "";
                    lblPreviousDateApproved.Text = approval[(approval.Table as ApprovalTable).PreviousDateApprovedColumn.ColumnName] != DBNull.Value ? approval.PreviousDateApproved.ToString("yyyy-MM-dd") : "";
                    lblPreviousApprovedBy.Text = approval[(approval.Table as ApprovalTable).PreviousApprovedByColumn.ColumnName] != DBNull.Value ? approval.PreviousApprovedBy : "";
                    lblPreviousResultApproved.Text = approval[(approval.Table as ApprovalTable).PreviousResultApprovedColumn.ColumnName] != DBNull.Value ? (approval.PreviousResultApproved ? "已批准" : "未批准") : "";

                    ApplicationRow application = CentralOffice.Task.BusinessActions.Applications.GetById(approval.ApplicationId);
                    if (!application.IsApplicationExecutorNull())
                    {
                        txtExecutor.Value = application.ApplicationExecutor;
                        lblExecutor.Text = application.ApplicationExecutor;
                    }

                    ApprovalTable approvals = CentralOffice.Task.BusinessActions.Approvals.GetByMasterId(approval.ApplicationId);

                    if (!approval.IsFinal)
                    {
                        ApprovalRow q = approvals.SingleOrDefault(a => (!a.IsPreviousStepNull()) && a.PreviousStep == approval.Id);
                        if (q != null)
                        {
                            txtApprovedBy.Value = q.ApprovedBy;
                            txtApprovedByReadOnly.Value = q.ApprovedBy;
                            txtContentText.Text = q.ContentText;
                        }
                    }

                    if (HttpContext.Current.Request.QueryString["op"] == "u")
                    {
                        txtOpinion.Text = approval.IsOpinionNull() ? "" : approval.Opinion;

                        ApprovalRow approvalNext = CentralOffice.Task.BusinessActions.Approvals.GetByPreviousStepId(approval.Id);
                        if (approvalNext != null)
                        {
                            txtApprovedBy.Value = approvalNext.ApprovedBy;
                            txtApprovedByReadOnly.Value = approvalNext.ApprovedBy;
                            txtContentText.Text = approvalNext.ContentText;
                            chkIsFinal.Checked = false;
                        }
                        else
                        {

                            //txtApprovedBy.Value = application.IsApplicationExecutorNull() ? "": application.ApplicationExecutor;
                            //txtApprovedByReadOnly.Value = txtApprovedBy.Value;
                            //if(application == 
                            chkIsFinal.Checked = true;
                        }
                    }

                    if (!approval.IsStepIdNull())
                    {
                        chkIsFinal.Visible = false;
                        UpdatePanel1.Visible = false;
                        txtContentText.Visible = false;
                        jsApproval.Text = "<script type=\"text/javascript\"> $get('clearApprovedBy').style.display='none';$get('trIsFinal').firstChild.innerHTML='';   $get('trApprovalBy').firstChild.innerHTML='';$get('trApprovContentBy').firstChild.innerHTML='';</script>";
                    }


                    // 周付款计划
                    #region

                    if (application.Version == 2)
                    {
                        divPaymentList.Visible = true;
                        gvPaymentItem.Visible = true;

                        PaymentItemDataSet ds = new PaymentItemDataSet();
                        System.IO.StringReader sw = new System.IO.StringReader(application.Description);
                        ds.ReadXml(sw);

                        Session["PaymentItemDataSet"] = ds;

                        DataView dv = new DataView(ds.Payment, " IsApproved = 1", null, DataViewRowState.CurrentRows);

                        gvPaymentItem.DataSource = dv;// ds.Payment;
                        gvPaymentItem.DataBind();

                        string opinion = "";
                        foreach (PaymentRow pr in ds.Payment)
                        {
                            if ( pr.IsApproved)
                            {
                                opinion += "同意给" + pr.Customer + "付款" + pr.ApprovedDue + "元|";
                            }
                            else
                            {
                                //opinion += "不同意给" + pr.Customer + "付款" + pr.ApprovedDue + "元|";
                            }
                        }
                        if (opinion.Length > 0)
                        {
                            txtOpinion.Text = opinion.TrimEnd('|').Replace("|", System.Environment.NewLine);
                        }
                    }

                    #endregion
                }
                else
                {
                    btnSave.Visible = false;
                    Button1.Visible = false;
                    lblJavaScript.Text = "<script type=\"text/javascript\">alert('因为审批的修改，本步已审批已取消，直接关闭本页即可 ！');window.close();</script>";
                    //Response.Redirect("ApplicationApprove.aspx");
                }
            }
        }

        protected void btnAccept_Click(object sender, EventArgs e)
        {
            string approvalId = HttpContext.Current.Request.QueryString["id"];
            ApprovalRow approval = CentralOffice.Task.BusinessActions.Approvals.GetById(new Guid(approvalId));

            // 修改当前审批步骤
            ApprovalDataSet approvalDataSet = approval.Table.DataSet as ApprovalDataSet;
             
            approval.DateApproved = DateTime.Now;
            approval.IsFinal = chkIsFinal.Checked;
            approval.Opinion = txtOpinion.Text == "不同意" ? "同意" : txtOpinion.Text;
            approval.ResultApproved = true;
            approval.LastModifiedBy = ApplicationContext.ActualUserId;
            approval.ModifiedTime = DateTime.Now;
            //approval.IsActive = true;
            if (approval.Opinion == "终审不同意")
            {
                if (approval.IsFinal)
                {
                    approval.Opinion = "终审同意";
                }
                else
                {
                    approval.Opinion = "同意";
                }
            }

            approval.IsApproved = true;
            if (approval.IsNextStepIsApprovedNull())
            {
                approval.NextStepIsApproved = false;
            }
            if (approval.IsSequenceNumberNull())
            {
                approval.SequenceNumber = 1;
            }

            string fileName = SaveFile(SiteUtil.GetTaskFilesPath(), fileAttachments);
            if (fileName.Length > 0)
            {
                approval.ApprovalAttachments = fileName;
            }


            // 修改申请
            ApplicationRow application = CentralOffice.Task.BusinessActions.Applications.GetById(approval.ApplicationId);
            ApplicationDataSet applicationDataSet = application.Table.DataSet as ApplicationDataSet;

            


            // 如果不是终审，表示有下一步
            if (!chkIsFinal.Checked)//|| txtApprovedBy.Value.Length > 0
            {
                ApprovalTable approvals = CentralOffice.Task.BusinessActions.Approvals.GetByMasterId(approval.ApplicationId);
                ApprovalRow q = approvals.SingleOrDefault(a => (!a.IsPreviousStepNull()) && a.PreviousStep == approval.Id);

                #region 如果是修改本条审批
                // 如果是修改本条审批
                if (HttpContext.Current.Request.QueryString["op"] == "u")
                {
                    #region 处理下步审批
                    if (txtApprovedBy.Value.Length > 0)
                    {
                        // 判断下一步的审批者  // 2010-07-27 修改了 approvalNext的值，改为q
                        ApprovalRow approvalNext = q; // CentralOffice.Task.BusinessActions.Approvals.GetByPreviousStepId(approval.Id);
                        // 如果修改了下一步审批者
                        if (approvalNext != null)
                        {
                            if (approvalNext.ApprovedBy != txtApprovedBy.Value)
                            {
                                approvalNext.ApprovedBy = txtApprovedBy.Value;
                                approvalNext.LastModifiedBy = ApplicationContext.ActualUserId;
                                approvalNext.ModifiedTime = DateTime.Now;
                            }
                            if (approvalNext.ContentText != txtContentText.Text)
                            {
                                approvalNext.ContentText = txtContentText.Text;
                                approvalNext.LastModifiedBy = ApplicationContext.ActualUserId;
                                approvalNext.ModifiedTime = DateTime.Now;
                            }
                            //approvalNext.IsApproved = true;
                            if (approvalNext.IsNextStepIsApprovedNull())
                            {
                                approvalNext.NextStepIsApproved = false;
                            }
                            if (approvalNext.IsSequenceNumberNull())
                            {
                                approvalNext.SequenceNumber = 1;
                            }


                            approvalNext.CreatedTime = DateTime.Now; // 2010-7-16 加，用于修改下一步审批流程的审批时间，表示下一步审批开始计时了。
                            approvalNext.IsActive = true;
                            approvalNext.IsDeleted = false;

                            CentralOffice.Task.BusinessActions.Approvals.Update(approvalNext.Table.DataSet);
                        }
                        else
                        {
                            if (approval.IsStepIdNull())
                            {
                                AddApprovalRow(application.UrgencyDegree, approval, txtApprovedBy.Value, txtContentText.Text);
                            }
                            else
                            {
                                // 如果是固定流程，则将下一步启动。
                                q.CreatedTime = DateTime.Now; // 2010-7-16 加，用于修改下一步审批流程的审批时间，表示下一步审批开始计时了。
                                q.IsActive = true;
                                q.IsDeleted = false;
                                CentralOffice.Task.BusinessActions.Approvals.Update(q.Table.DataSet);
                            }
                        }
                    }
                    #endregion
                    // 
                    if (application.Status == EnumUtil.GetInt32(SiteConstants.ApprovalStatus, CategoryDataSourceType.Xml, "否决")
                        || application.Status == EnumUtil.GetInt32(SiteConstants.ApprovalStatus, CategoryDataSourceType.Xml, "通过"))
                    {
                        application.Status = EnumUtil.GetInt32(SiteConstants.ApprovalStatus, CategoryDataSourceType.Xml, "在审");
                    }

                }
                else
                {
                    if (approval.IsStepIdNull())
                    {
                        // 如果不是终审，要添加一条新的审批步骤
                        AddApprovalRow(application.UrgencyDegree, approval, txtApprovedBy.Value, txtContentText.Text);
                    }
                    else
                    {
                        // 如果是固定流程，则将下一步启动。
                        q.IsActive = true;
                        q.IsDeleted = false;
                        q.CreatedTime = DateTime.Now; // 2010-7-16 加，用于修改下一步审批流程的审批时间，表示下一步审批开始计时了。

                        string interval = SiteUtil.GetConfigurationItem(application.UrgencyDegree, SiteConstants.Priority).Data;
                        q.WarningDate = DateTime.Now.AddMinutes(Convert.ToDouble(interval));

                        CentralOffice.Task.BusinessActions.Approvals.Update(q.Table.DataSet);
                    }
                    // 更新申请状态为在审
                    application.Status = EnumUtil.GetInt32(SiteConstants.ApprovalStatus, CategoryDataSourceType.Xml, "在审");
                }

                #endregion
            }
            else
            {
                // 如果是终审，更新申请状态为通过
                application.Status = EnumUtil.GetInt32(SiteConstants.ApprovalStatus, CategoryDataSourceType.Xml, "通过");
                //application.ApplicationExecutor = txtApprovedBy.Value;
                // 如果是修改本条审批
                if (HttpContext.Current.Request.QueryString["op"] == "u")
                {
                    // 判断下一步的审批,有的话删掉
                    int cnt = CentralOffice.Task.BusinessActions.Approvals.DeleteByPreviousStepId(approval.Id);
                }

                // 
                if (approval.Opinion == "同意")
                {
                    approval.Opinion = "终审同意";
                }

                if (approval.Opinion == "终审不同意")
                {
                    approval.Opinion = "终审同意";
                }
            }

            application.LastModifiedBy = ApplicationContext.ActualUserId;
            application.ModifiedTime = DateTime.Now;

            if (application.Version == 2)
            {
                PaymentItemDataSet ds = Session["PaymentItemDataSet"] as PaymentItemDataSet;
                if (ds == null)
                {
                    Response.Redirect("~/default.aspx");
                    return;
                }

                foreach (GridViewRow gvr in gvPaymentItem.Rows)
                {
                    if (gvr.RowType == DataControlRowType.DataRow)
                    {
                        Guid id = (Guid)gvPaymentItem.DataKeys[gvr.DataItemIndex].Value;
                        PaymentRow paymentItem = ds.Payment.SingleOrDefault(r => r.Id == id);

                        CheckBox cb = gvr.Cells[0].Controls[0] as CheckBox;
                        if (cb != null)
                        {
                            if (!cb.Checked)
                            {
                                if (paymentItem != null)
                                {
                                    paymentItem.Status = Convert.ToByte(EnumUtil.GetInt32(SiteConstants.ApprovalStatus, CategoryDataSourceType.Xml, "否决"));

                                    paymentItem.IsApproved = false;
                                    
                                }
                            }
                            else
                            {
                                paymentItem.IsApproved = true;
                            }
                        }

                        TextBox txt = gvr.Cells[4].Controls[0] as TextBox;
                        if (txt != null)
                        {
                            if (paymentItem != null)
                            {
                                paymentItem.ApprovedDue = Convert.ToDecimal(txt.Text);

                                if (!cb.Checked)
                                {
                                    paymentItem.ApprovedDue = 0m;
                                }
                            }


                        }

                        paymentItem.ApprovedBy = ApplicationContext.ActualUserName;
                        paymentItem.ApprovedDate = DateTime.Now;

                    }
                }

                application.Description = ds.GetXml();
                approval.Description = application.Description;
            }

            CentralOffice.Task.BusinessActions.Applications.Update(applicationDataSet, approvalDataSet);
            
            // 
            if (!approval.IsPreviousStepNull())
            {
                ApprovalRow approvalPrevious = CentralOffice.Task.BusinessActions.Approvals.GetById(approval.PreviousStep);
                if (approvalPrevious != null)
                {
                    approvalPrevious.NextStepIsApproved = true;
                    CentralOffice.Task.BusinessActions.Approvals.Update(approvalPrevious.Table.DataSet);
                }
            }

            if (!chkIsFinal.Checked)//|| txtApprovedBy.Value.Length > 0
            {
            }
            else
            {
                SendSms(application.Applicant, "您的申请：" + application.Name + " 已于 " + DateTime.Now.ToString() + "审批通过。");
            }

            Response.Redirect("ApplicationApprove.aspx");
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            string approvalId = HttpContext.Current.Request.QueryString["id"];
            ApprovalRow approval = CentralOffice.Task.BusinessActions.Approvals.GetById(new Guid(approvalId));

            // 更新审批信息
            ApprovalDataSet approvalDataSet = approval.Table.DataSet as ApprovalDataSet;

            if (HttpContext.Current.Request.QueryString["op"] == "u")
            {
                //if (approval.Opinion != txtOpinion.Text.Trim()
                //    || approval.IsFinal != chkIsFinal.Checked
                //    || approval.ResultApproved == true)
                //{
                //    approval.DateApproved = DateTime.Now;
                //}
                approval.DateApproved = DateTime.Now;
            }
            else
            {
                approval.DateApproved = DateTime.Now;
            }
            approval.IsFinal = chkIsFinal.Checked;
            approval.Opinion = txtOpinion.Text == "同意" || txtOpinion.Text == "" ? "不同意" : txtOpinion.Text;
            approval.ResultApproved = false;
            approval.LastModifiedBy = ApplicationContext.ActualUserId;
            approval.ModifiedTime = DateTime.Now;

            approval.IsApproved = true;
            if (approval.IsNextStepIsApprovedNull())
            {
                approval.NextStepIsApproved = false;
            }
            if (approval.IsSequenceNumberNull())
            {
                approval.SequenceNumber = 1;
            }

            if (chkIsFinal.Checked && approval.IsFinal && approval.Opinion == "不同意")
            {
                approval.Opinion = "终审不同意";
            }

            if (chkIsFinal.Checked && approval.IsFinal && approval.Opinion  == "终审同意")
            {
                approval.Opinion = "终审不同意";
            }


            string fileName = SaveFile(SiteUtil.GetTaskFilesPath(), fileAttachments);
            if (fileName.Length > 0)
            {
                approval.ApprovalAttachments = fileName;
            }

            // 更新申请信息
            ApplicationRow application = CentralOffice.Task.BusinessActions.Applications.GetById(approval.ApplicationId);
            application.Status = EnumUtil.GetInt32(SiteConstants.ApprovalStatus, CategoryDataSourceType.Xml, "否决");
            application.LastModifiedBy = ApplicationContext.ActualUserId;
            application.ModifiedTime = DateTime.Now;

            ApplicationDataSet applicationDataSet = application.Table.DataSet as ApplicationDataSet;
            CentralOffice.Task.BusinessActions.Applications.Update(applicationDataSet, approvalDataSet);

            // 删除 以后的审批步骤
            //CentralOffice.Task.BusinessActions.Approvals.Delete(String.Format("DELETE FROM Tasks.Approvals WHERE ApplicationId = '{0}' AND CreatedTime > '{1}' AND ResultApproved IS NULL ", approval.ApplicationId.ToString(), approval.CreatedTime.AddSeconds(1).ToString()), null, false);

            // UPDATE [Tasks].[Approvals]  SET IsDeleted = 1 WHERE ApplicationId = @ApplicationId
            //CentralOffice.Task.BusinessActions.Approvals.Delete(String.Format("DELETE FROM Tasks.Approvals WHERE ApplicationId = '{0}' AND SequenceNumber > '{1}' AND ResultApproved IS NULL ", approval.ApplicationId.ToString(), approval.SequenceNumber.ToString()), null, false);

            // 2010-7-26 修改
            CentralOffice.Task.BusinessActions.Approvals.Delete(String.Format("UPDATE [Tasks].[Approvals]  SET IsDeleted = 1  WHERE ApplicationId = '{0}' AND SequenceNumber > '{1}' AND ResultApproved IS NULL ", approval.ApplicationId.ToString(), approval.SequenceNumber.ToString()), null, false);


            if (!approval.IsPreviousStepNull())
            {
                ApprovalRow approvalPrevious = CentralOffice.Task.BusinessActions.Approvals.GetById(approval.PreviousStep);
                if (approvalPrevious != null)
                {
                    approvalPrevious.NextStepIsApproved = true;
                    CentralOffice.Task.BusinessActions.Approvals.Update(approvalPrevious.Table.DataSet);
                }
            }

            SendSms(application.Applicant, "您的申请：" + application.Name + " 已于 " + DateTime.Now.ToString() + "被否决，请及时查看。");

            Response.Redirect("ApplicationApprove.aspx");
        }

        private static void AddApprovalRow(int urgencyDegree, ApprovalRow previousApproval, string approvedBy, string approvedContext)
        {
            ApprovalDataSet approvalDataSet = previousApproval.Table.DataSet as ApprovalDataSet;

            ApprovalRow approval = approvalDataSet.Approvals.NewApprovalsRow();
            SiteUtil.PopulateCommonField(approval, Guid.NewGuid());

            approval.ApplicationId = previousApproval.ApplicationId;
            approval.ApprovedBy = approvedBy;
            //approval.DateApproved = txtDateApproved.Text;
            approval.ContentText = approvedContext;
            //approval.Opinion = txtOpinion.Text;
            //approval.ResultApproved = txtResultApproved.Text;
            approval.PreviousStep = previousApproval.Id;
            approval.IsFinal = false;
            approval.NextStepIsApproved = false;
            approval.IsApproved = false;
            approval.SequenceNumber = previousApproval.IsSequenceNumberNull() ? 1 : previousApproval.SequenceNumber + 1;

            string interval = SiteUtil.GetConfigurationItem(urgencyDegree, SiteConstants.Priority).Data;
            approval.WarningDate = DateTime.Now.AddMinutes(Convert.ToDouble(interval));

            approvalDataSet.Approvals.AddApprovalsRow(approval);
        }

        protected void btnShowPopup_Click(object sender, EventArgs e)
        {
            string[] assignedBy = null; //txtApprovedBy.Value.Split(',');
            LinkButton btn = sender as LinkButton;
            if (btn != null)
            {
                txtSelectedObject.Value = btn.CommandName;

                if (btn.CommandName == "Executor")
                {
                    //assignedBy = txtExecutor.Value.Split(',');
                }
                else
                {
                    assignedBy = txtApprovedBy.Value.Split(',');
                }
            }

            tvEmp.Nodes.Clear();
            HumanResources.HumanResourcesHelper.PopulateEmployeeTree(tvEmp, true, assignedBy);

            updPnlDepartment.Update();
            mdlDetailView.Show();
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            // 保存弹出窗口所更新的信息
            string employees = "";
            string employeesId = "";

            if (tvEmp.CheckedNodes.Count > 0)
            {
                foreach (TreeNode node in tvEmp.CheckedNodes)
                {
                    if (!node.Text.StartsWith("["))
                    {
                        employees += node.Text + ",";
                        employeesId += node.Value + ",";
                    }
                }
            }

            if (txtSelectedObject.Value == "Executor")
            {
                //txtExecutor.Value = employees.Trim(',');
                //txtApplicant.Value = departmentsId;
                //txtExecutor.Value = employees.Trim(',');
            }
            else
            {
                txtApprovedByReadOnly.Value = employees.Trim(',');
                txtApprovedBy.Value = employees.Trim(',');
            }
        }

        protected void tvEmp_Load(object sender, EventArgs e)
        {
            this.tvEmp.Attributes.Add("OnClick", "OnTreeNodeChecked(event)");
        }

        private string SaveFile(string rootDir, FileUpload file)
        {
            string fileName = "";

            string path = Server.MapPath(rootDir);
            if (file.HasFile)
            {
                //file.SaveAs(path + file.FileName);
                //fileName = rootDir + file.FileName;
                var fn = SiteUtil.GetUploadFileName(path, file.FileName);
                file.SaveAs(fn);
                fileName = rootDir + fn.Substring(fn.LastIndexOf('\\') + 1);
            }
            else
            {

            }
            return fileName;
        }

        private void SendSms(string receiver, string message)
        {
            SmsDataSet smsBody = null;
            SmsBodyRow smsbodyrow = (new SmsDataSet()).sms_body.Newsms_bodyRow();

            smsbodyrow.FromId = ApplicationContext.ActualUserId.ToString();
            smsbodyrow.SmsType = "1";
            smsbodyrow.Content = message;
            smsbodyrow.SendTime = DateTime.Now;
            smsbodyrow.RemindUrl = "无";
            smsbodyrow.sGuid = Guid.NewGuid().ToString();
            smsbodyrow.Table.Rows.Add(smsbodyrow);
            smsBody = smsbodyrow.Table.DataSet as SmsDataSet;

            CentralOffice.MyTable.BusinessActions.SmsBody.Update(smsBody);

            smsbodyrow = CentralOffice.MyTable.BusinessActions.SmsBody.GetById(new Guid(smsbodyrow.sGuid));
            SmsDataSet smsds = new SmsDataSet();
            SmsRow smsrowTmp = smsds.sms.NewsmsRow();

            List<MembershipUserEx> employees = UserManager.GetAllUsersWithEmp(1);
            if (employees == null || employees.Count == 0)
                return;

            MembershipUserEx emp = employees.FirstOrDefault(e => e.Name == receiver);

            if (emp == null)
            {
                smsrowTmp.ToId = emp.EmployeeId.ToString();
                smsrowTmp.ToName = emp.Name;
                smsrowTmp.RemindFlag = "0";
                smsrowTmp.DeleteFlag = "0";
                smsrowTmp.BodyId = smsbodyrow.BodyId;
                smsds.sms.Rows.Add(smsrowTmp);

                CentralOffice.MyTable.BusinessActions.Sms.Update(smsds);
            }
        }

    }
}
